import { createStore } from "vuex";

export default createStore({
  state: {
    count: 0,
    user: null, // 用户认证状态
    token: null // JWT token（如果有）
  },
  mutations: {
    increment(state) {
      state.count++;
    },
    // 用户登录状态更新
    SET_USER(state, user) {
      state.user = user;
      // 同时存储到 localStorage 以保持会话
      localStorage.setItem("user", JSON.stringify(user));
    },
    // 设置认证 token
    SET_TOKEN(state, token) {
      state.token = token;
      localStorage.setItem("token", token);
    },
    // 用户登出
    LOGOUT(state) {
      state.user = null;
      state.token = null;
      localStorage.removeItem("user");
      localStorage.removeItem("token");
    }
  },
  actions: {
    increment({ commit }) {
      commit("increment");
    },
    // 登录操作
    login({ commit }, { user, token }) {
      commit("SET_USER", user);
      commit("SET_TOKEN", token);
    },
    // 登出操作
    logout({ commit }) {
      commit("LOGOUT");
    },
    // 从本地存储恢复用户会话
    initSession({ commit }) {
      const user = localStorage.getItem("user");
      const token = localStorage.getItem("token");
      
      if (user && token) {
        commit("SET_USER", JSON.parse(user));
        commit("SET_TOKEN", token);
      }
    }
  },
  getters: {
    doubleCount: state => state.count * 2,
    // 获取当前用户
    currentUser: state => state.user,
    // 检查用户是否已登录
    isAuthenticated: state => !!state.user,
    // 获取认证 token
    authToken: state => state.token
  }
});